/*
 * Atomic Predicates for Transformers
 * 
 * Copyright (c) 2015 UNIVERSITY OF TEXAS AUSTIN. All rights reserved. Developed
 * by: HONGKUN YANG and SIMON S. LAM http://www.cs.utexas.edu/users/lam/NRL/
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * with the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimers.
 * 
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimers in the documentation
 * and/or other materials provided with the distribution.
 * 
 * 3. Neither the name of the UNIVERSITY OF TEXAS AUSTIN nor the names of the
 * developers may be used to endorse or promote products derived from this
 * Software without specific prior written permission.
 * 
 * 4. Any report or paper describing results derived from using any part of this
 * Software must cite the following publication of the developers: Hongkun Yang
 * and Simon S. Lam, Scalable Verification of Networks With Packet Transformers
 * Using Atomic Predicates, IEEE/ACM Transactions on Networking, October 2017,
 * Volume 25, No. 5, pages 2900-2915 (first published as IEEE Early Access
 * Article, July 2017, Digital Object Identifier: 10.1109/TNET.2017.2720172).
 * 
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH
 * THE SOFTWARE.
 */
package transformer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;

import common.APComputer;
import common.PositionTuple;

public class IPinIPTunnelConeAP {

    NetworkCOVEAP net;
    String root;
    HashSet<String> all_tier1s;

    ArrayList<String> tier1s;
    ArrayList<String> others;

    public IPinIPTunnelConeAP(String netname, String root, String tier1File) throws IOException, ClassNotFoundException
    {

        String serialized = netname + "ap.ser";
        if(new File(serialized).isFile()) 
        {
            net = NetworkCOVEAP.read_object(serialized);
        }else
        {
            //String edgerouterfile = networkname+"edge";
            net = new NetworkCOVEAP(netname, null);
            net.save_object();
        }

        this.root = root;

        all_tier1s = new HashSet<String> ();
        BufferedReader br = new BufferedReader(new FileReader(new File(tier1File)));
        String line;
        while ((line = br.readLine()) != null) {
            String edge = line.trim();
            if(edge.length() > 0)
            {
                all_tier1s.add(edge);
            }
        }
        br.close();

        tier1s = new ArrayList<String> ();
        others = new ArrayList<String> ();

        for(String dname : net.boxes.keySet())
        {
            if(((Device) net.boxes.get(dname)).has_valid_nataddr())
                if(all_tier1s.contains(dname))
                {
                    tier1s.add(dname);
                }else
                {
                    if(!dname.equals(root))
                    {
                        others.add(dname);
                    }
                }
        }

        System.out.println(tier1s.size()+" tier1 ASes in the cone");
        System.out.println(others.size()+" other ASes in the cone");


    }

    /**
     * add tunnels and compute atomic predicates
     * @param tunnel_num
     * this can only be used when the network is a provider cone
     */
    public void add_tunnels(int tunnel_num)
    {
        net.ini_IPinIP();
        net.remove_null_routes();

        int cnt = 0;
        for(int i = 0; i < tier1s.size(); i++)
        {
            for(int j = 0; j < others.size(); j ++)
            {
                if(cnt >= tunnel_num)
                {
                    break;
                }else
                {
                    cnt++;
                    net.add_ipinip_tunnel(root, others.get(j), tier1s.get(i));
                }
            }
        }

        System.out.println(cnt + " tunnels added");

        net.ap_first_iter();

        net.ap_ipinip();
    }

    private void add_tunnels(ArrayList<String[]> tunnels, int tunnel_num)
    {
        net.ini_IPinIP();
        net.remove_null_routes();
        for(int i = 0; i < tunnel_num; i ++)
        {
            String[] one_tunnel = tunnels.get(i);
            net.add_ipinip_tunnel(one_tunnel[0], one_tunnel[1], one_tunnel[2]);
        }

        net.ap_first_iter();
        net.ap_ipinip();
    }

    /**
     * read tunnel specs from the given file into a list, add given number of 
     * tunnels selected sequentielly from the list. 
     * @param tunnel_file
     * @param tunnel_num
     * @throws IOException 
     */
    public void add_tunnel_from_file(String tunnel_file, int tunnel_num) throws IOException {
        FileInputStream fis;
        ArrayList<String[]> tunnels = new ArrayList<String[]>();
        try {
            fis = new FileInputStream(new File(tunnel_file));

            //Construct BufferedReader from InputStreamReader
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));

            String line = null;
            while ((line = br.readLine()) != null) {
                tunnels.add(line.trim().split(" "));
            }

            br.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        
        add_tunnels(tunnels, tunnel_num);


    }

    public void write_tunnel_info() throws FileNotFoundException
    {

        PrintWriter pw = new PrintWriter(new File(net.name + "_" + root+"_ipiniptunnels"));
        ArrayList<String> tunnels = new ArrayList<String>();
        for(int i = 0; i < tier1s.size(); i++)
        {
            for(int j = 0; j < others.size(); j ++)
            {
                tunnels.add(root+ " " +others.get(j)+ " " + tier1s.get(i));
            }
        }

        Collections.shuffle(tunnels);
        for(String t : tunnels){
            pw.println(t);
        }

        System.out.println(tunnels.size() + " tunnels added");
        pw.close();

    }

    private void add_one_tunnel_update(ArrayList<String[]> tunnels, int tunnel_ind)
    {
        String[] tunnel = tunnels.get(tunnel_ind);
        net.add_ipinip_tunnel_update(tunnel[0], tunnel[1], tunnel[2]);
    }

    public void update()
    {

        ArrayList<String[]> tunnels = new ArrayList<String[]> ();
        int tunnel_num = 40;
        int cnt = 0;
        for(int i = 0; i < tier1s.size(); i++)
        {
            for(int j = 0; j < others.size(); j ++)
            {
                if(cnt >= tunnel_num)
                {
                    break;
                }else
                {
                    cnt++;
                    String[] one_tunnel = new String[3];
                    one_tunnel[0] = root;
                    one_tunnel[1] = others.get(j);
                    one_tunnel[2] = tier1s.get(i);
                    tunnels.add(one_tunnel);
                    //net.add_ipinip_tunnel(root, others.get(j), tier1s.get(i));
                }
            }
        }



        add_tunnels(tunnels, tunnel_num-1);

        add_one_tunnel_update(tunnels, tunnel_num-1);

        double ap_update = net.ap_ipinip_update();

        //double tree_compute = compute_trees();

        System.out.println("AP Update Time:" + ap_update);
        //System.out.println("Recompute Tree:" + tree_compute);
    }

    public double compute_trees(PrintWriter pw)
    {
        HashSet<PositionTuple> usedpts = new HashSet<PositionTuple> ();
        for(PositionTuple pt : net.getallactiveports())
        {
            System.out.println(pt);
            if(pt.getPortName().equals(root))
            {
                usedpts.add(pt);
            }
        }

        System.out.println("Port" + usedpts + " are used for computation");


        return StateTransferAP.compute_trees_anypkt(net, usedpts, pw);


    }

    public static void test_ipinip(String netname, int tunnelnum) throws IOException, ClassNotFoundException
    {
        IPinIPTunnelConeAP TC = new IPinIPTunnelConeAP(netname, netname, "tier1");

        TC.add_tunnels(tunnelnum);

        String outputfolder = "ipinipconeap_" + TC.root + "/";
        File thedir = new File(outputfolder);
        if(!thedir.exists())
        {
            thedir.mkdir();
        }

        PrintWriter pw = new PrintWriter(new File(outputfolder + tunnelnum +"tunnels"));
        TC.compute_trees(pw);
        pw.close();

    }

    public static void test() throws IOException, ClassNotFoundException
    {
        IPinIPTunnelConeAP TC = new IPinIPTunnelConeAP("cluster18", "21280", "tier1");

        NetworkCOVEAP net = TC.net;
        net.ini_IPinIP();
        net.remove_null_routes();
        net.ap_first_iter();

        //net.add_ipinip_tunnel("12455", "13224", "21280");
        net.add_ipinip_tunnel("4558", "37219", "37684");
        net.add_ipinip_tunnel("33770", "33771", "36866");

        net.ap_ipinip();

        String outputfolder = "ipinipconeap_" + TC.root + "/";
        File thedir = new File(outputfolder);
        if(!thedir.exists())
        {
            thedir.mkdir();
        }

        PrintWriter pw = new PrintWriter(new File(outputfolder +"2tunnels"));
        TC.compute_trees(pw);
        pw.close();

    }

    public void update_port_predicate_ipinip()
    {
        ArrayList<int[]> updates = new ArrayList<int[]> ();
        add_tunnels(40);

        HashSet<Integer> predicates = new HashSet<Integer>();
        for(Box b : net.boxes.values())
        {
            int count = 0;
            // for each router, pick two port predicates
            int[] update = new int[2];

            if(b instanceof Device)
            {
                int size = ((Device) b).fwbdds.size();
                int[] picks = NetworkAP.randPicksRange(1, size);

                for(int port_predicate : ((Device) b).fwbdds.values())
                {
                    count ++;
                    if(count == picks[0])
                    {
                        update[0] = port_predicate;
                    }else{
                        if(count == picks[1])
                        {
                            update[1] = port_predicate;
                            updates.add(update);
                        }
                        predicates.add(port_predicate);
                    }
                }
            }
        }

        APComputer apc = new APComputer(net.bddengine);
        net.apc = apc;

        ArrayList<IPinIP> tunnels = new ArrayList<IPinIP> ();
        for(Box b : net.boxes.values())
        {
            Device d = (Device) b;
            if(d.ip_in_ip != null)
            {
                tunnels.add(d.ip_in_ip);
            }
        }

        int size = apc.addPredicates(new ArrayList<Integer>(predicates));
        apc.computeExpressions();
        net.compute_ap_ipinip(tunnels);


        long update_time = 0;

        for(int[] update : updates)
        {
            long t1 = System.currentTimeMillis();

            apc.update_r(update[1]);
            apc.update_a(update[0]);

            net.compute_ap_ipinip(tunnels);;
            long t2 = System.currentTimeMillis();

            update_time += t2-t1;

            System.out.println(t2-t1);
        }

        System.out.println("update time: " + (1.0*update_time/updates.size())+ " ms");

    }

    public static void main(String[] args) throws IOException, ClassNotFoundException
    {
        //test();
        //test_ipinip(args[0], Integer.parseInt(args[1]));
        IPinIPTunnelConeAP TC = new IPinIPTunnelConeAP("52941", "52941", "tier1");
        TC.write_tunnel_info();
        //TC.update();
        //TC.update_port_predicate_ipinip();
    }

}
